import React, { useState } from 'react';
import axios from 'axios';

const UpdatePasswordForm = ({ userId }) => {
    const [oldPassword, setOldPassword] = useState('');
    const [newPassword, setNewPassword] = useState('');
    const [message, setMessage] = useState('');

    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            const response = await axios.put(`/update-password/${userId}`, {
                oldPassword,
                newPassword
            });

            setMessage(response.data);
            setOldPassword('');
            setNewPassword('');
        } catch (error) {
            setMessage("Failed to update password. Please try again.");
            console.error(error);
        }
    };

    return (
        <form onSubmit={handleSubmit}>
            <label htmlFor="oldPassword">Old Password:</label>
            <input
                type="password"
                id="oldPassword"
                value={oldPassword}
                onChange={(e) => setOldPassword(e.target.value)}
                required
            />
            <label htmlFor="newPassword">New Password:</label>
            <input
                type="password"
                id="newPassword"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                required
            />
            <button type="submit">Update Password</button>
            {message && <p>{message}</p>}
        </form>
    );
};

export default UpdatePasswordForm;